import React, { useState, useEffect } from 'react'
import {
  Table,
  Input,
  Button,
  Modal,
  Form,
  Popconfirm,
  message,
  DatePicker,
  Select,
} from 'antd'
import '../style/goods.scss'
import {
  PlusOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import baseApi from '../api/base'
import { useSelector, useDispatch } from 'react-redux'
import { changeVal, loadGoods, loadGoods2 } from '@/store/dic'

const { Search, TextArea  } = Input

function Goods (props) {
  const dispatch = useDispatch()
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
    },
    {
      title: '生产日期',
      dataIndex: 'produce_date',
      key: 'produce_date',
      ellipsis: true,
    },
    {
      title: '分类',
      dataIndex: 'sort',
      key: 'sort',
      ellipsis: true,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      ellipsis: true,
    },
    {
      title: '上架状态',
      dataIndex: 'put_status',
      key: 'put_status',
      ellipsis: true,
    },
    {
      title: '上架日期',
      dataIndex: 'put_date',
      key: 'put_date',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      key: 'updatetime',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 150,
      render: (_, r) =>
        <div className='wrap_operate'>
          <Button type="link" onClick={() => onEdit(r)}>编辑</Button>
          <Popconfirm
            title="确认删除此条数据吗？"
            onConfirm={() => onDel(r)}>
            <Button danger type="link">删除</Button>
          </Popconfirm>
        </div>

    },
  ]
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const sortList = useSelector((state) => state.dic.sortList)
  const unitList = useSelector((state) => state.dic.unitList)
  const statusList = useSelector((state) => state.dic.statusList)
  const [operateType, setOperateType] = useState('add')
  const [operateRow, setOperateRow] = useState({})
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [searchValue, setSearchValue] = useState('')

  useEffect(() => {
    // 模拟componentDidMount，即只运行一次该函数
    fetchData()
    // dispatch(loadGoods({ name: '香蕉' }))
    // dispatch(loadGoods2({ name: '橘子' }))
  }, [])

  const fetchData = () => {
    setLoading(true)
    const model = {
      name: searchValue
    }
    baseApi.findGoods(model).then(res => {
      setTableData(res.result)
    }).finally(() => {
      setLoading(false)
    })
  }

  const onChange = (e) => {
    setSearchValue(e.target.value)
  }

  const onAdd = () => {
    setOperateType('add')
    setIsModalVisible(true)
    // dispatch(changeVal({ title: "测试任务", age: 18 }))
  }

  const handleOk = () => {
    form.validateFields().then(v => {
      setConfirmLoading(true)
      const obj = {
        ...form.getFieldsValue()
      }
      obj.produce_date = obj.produce_date ? moment(obj.produce_date).format('YYYY-MM-DD') : null
      obj.put_date = obj.put_date ? moment(obj.put_date).format('YYYY-MM-DD') : null
      if (operateType === 'add') {
        baseApi.addGoods(obj).then(res => {
          message.success('添加成功')
          setIsModalVisible(false)
          fetchData()
        }).finally(() => {
          setConfirmLoading(false)
        })
      } else {
        obj.id = operateRow.id
        baseApi.updateGoods(obj).then(res => {
          message.success('编辑成功')
          setIsModalVisible(false)
          fetchData()
        }).finally(() => {
          setConfirmLoading(false)
        })
      }
    })
  }

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false)
  }

  const onEdit = (r) => {
    const o = JSON.parse(JSON.stringify(r))
    o.produce_date = o.produce_date ? moment(r.produce_date) : null
    o.put_date = o.put_date ? moment(r.put_date) : null
    setOperateRow(o)
    setOperateType('edit')
    setIsModalVisible(true)
    setTimeout(() => {
      form.setFieldsValue(o)
    }, 50)
  }

  const onDel = (r) => {
    baseApi.delGoods({ id: r.id }).then(res => {
      message.success('删除成功')
      fetchData()
    })
  }

  return (
    <div className="con">
      <div className="wrap_search">
        <Search
          placeholder="输入名称搜索..." 
          enterButton
          value={searchValue}
          onChange={(e) => onChange(e)}
          onSearch={(v) => fetchData()} />
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => onAdd()}>
          新增
        </Button>
      </div>
      <div className="wrap_table mt--10">
        <Table
          bordered
          loading={loading}
          scroll={{ y: 550 }}
          columns={columns}
          rowKey={(r) => r.id}
          dataSource={tableData} />
      </div>

      <Modal
        title={operateType === 'add' ? '新增商品' : '编辑商品'}
        visible={isModalVisible}
        destroyOnClose
        confirmLoading={confirmLoading}
        onOk={() => handleOk()}
        onCancel={() => handleCancel()}>
        <div>
        <Form
          name="form"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}>
          <Form.Item
            label="名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入名称',
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="生产日期"
            name="produce_date"
            rules={[
              {
                required: true,
                message: '请选择生产日期',
              },
            ]}>
            <DatePicker />
          </Form.Item>
          <Form.Item
            label="分类"
            name="sort"
            rules={[
              {
                required: true,
                message: '请选择分类',
              },
            ]}>
            <Select options={sortList}></Select>
          </Form.Item>
          <Form.Item
            label="单位"
            name="unit"
            rules={[
              {
                required: true,
                message: '请选择单位',
              },
            ]}>
            <Select options={unitList}></Select>
          </Form.Item>
          <Form.Item
            label="上架状态"
            name="put_status"
            rules={[
              {
                required: true,
                message: '请选择上架状态',
              },
            ]}>
            <Select options={statusList}></Select>
          </Form.Item>
          <Form.Item
            label="上架日期"
            name="put_date"
            rules={[
              {
                required: true,
                message: '请选择上架日期',
              },
            ]}>
            <DatePicker />
          </Form.Item>
          <Form.Item
            label="备注"
            name="remarks">
            <TextArea rows={4}/>
          </Form.Item>
        </Form>
        </div>
      </Modal>
    </div>
  )
}

export default Goods
